double tod(str) {
    return  Double.parseDouble(str)
}
int toi(str) {
    return  Integer.parseInt(str)
}
String intToIP(ipnum) {
    String ret =  String.format("%d.%d.%d.%d", (ipnum & 0xff),
            (ipnum >> 8 & 0xff), (ipnum >> 16 & 0xff),
            (ipnum >> 24 & 0xff));
    return ret;
}

String netmask(masklength) {
    int value = 0xffffffff << (32 - masklength)
    return intToIP(Integer.reverseBytes(value))
}

//hostname
def hostname = 'hostname'.execute().text

//处理器个数
def processorsize= ["bash", "-c", 'grep \'physical id\' /proc/cpuinfo | sort -u |wc -l'].execute().text.trim()
//单位：MHZ 
def processormhz=["bash", "-c", 'cat /proc/cpuinfo |grep MHz|uniq'].execute().text.split(":")[1].trim()

//disk info
def disks = [sys:[:],data:[:]]

('df '.execute() | 'grep md'.execute() ).text.eachLine {
    if(it.startsWith('/dev/md126p1') ) {  
        parts = it.split()     
        disks.sys.total = tod parts[1]
        disks.sys.used = tod parts[2]
    }
    if(it.startsWith('/dev/sdb') ) {  
        parts = it.split()     
        disks.data.total = tod parts[1]
        disks.data.used = tod parts[2]
    }
}

//mem info
def mem = [:]
'cat /proc/meminfo'.execute().text.eachLine {
    if(it.startsWith('MemTotal')) mem.MemTotal = tod it.split()[1]
    if(it.startsWith('MemFree')) mem.MemFree = tod it.split()[1]
    if(it.startsWith('Buffers')) mem.Buffers = tod it.split()[1]
    if(it.startsWith('Cached')) mem.Cached = tod it.split()[1]
}

mem.used = 1-(mem.MemFree+mem.Buffers+mem.Cached)/mem.MemTotal

def sys = [:]
sys.avgload=
["bash", "-c", "top -bi -d0.01 -n2 | grep Cpu | tail -n1 | cut -d ',' -f 4"].execute().text.eachLine {
    sys.avgload = tod it.split("%")[0].trim()
	sys.avgload=100-sys.avgload
}


//dns
def dns = []
'cat /etc/resolv.conf '.execute().text.eachLine {
		if(it!=null&&!it.equals("")&&it.startsWith('nameserver')){
				def str=it.split()
				if(str.length>1)
			    	dns << str[1]
		}
}

//ips
def ips = []
('ip -f inet addr '.execute()).text.eachLine {
    if(it.trim().startsWith('inet')) {
        tit = it.trim().split()
        eth = tit[4]
        if(eth != 'lo') {
            ip = tit[1].split('/')[0]
            mask = netmask(toi(tit[1].split('/')[1]))
            ips << ['ip':ip, 'if':eth, 'mask':mask]            
        }
    } 
}

//gateway
'ip -4 route'.execute().text.eachLine {
    if(it.startsWith('default')) {
        ips[0].gateway = it.split()[2]
    }
}



//net
def netflow = [:]
'cat /proc/net/dev'.execute().text.eachLine {
    it = it.trim()
    if(it.contains(':')) {
		ifname = it.substring(0, it.indexOf(':'))
		it = it.substring(it.indexOf(':') + 1)
        ps = it.split()
        netflow[ifname] = 
            ['rxbytes': tod(ps[0]), 'rxpackages': tod(ps[1]),
             'txbytes': tod(ps[8]), 'txpackages': tod(ps[9])]
    }
}


def updateHostName(def name) {
		 def out = new StringBuffer(), err = new StringBuffer()
		 def command='hostname '+name
		 def result= command.execute()
		 result.consumeProcessOutput(out, err)
		 result.waitForOrKill(1000)
		 return err.toString()
}

def updateHostDate(def date) {
    	 def out = new StringBuffer(), err = new StringBuffer()
		 def command='date -s \''+date+'\''
		 def result= ["bash", "-c", command].execute()	
 		 result.consumeProcessOutput(out, err)
		 result.waitForOrKill(1000)
		 return err.toString()
}

def updateHostIpNetMast(def eth,def ip,def netmast,def gateway) {
		 def out = new StringBuffer(), err = new StringBuffer()
		 def command='ifconfig '+eth+' '+ip+' netmask '+netmast 
		 def result= command.execute()	
 		 result.consumeProcessOutput(out, err)
		 result.waitForOrKill(1000)
		 def comm='route add -net default gw '+gateway 
		 def resu= comm.execute()	
 		 resu.consumeProcessOutput(out, err)
		 resu.waitForOrKill(1000)
		 def com='sed -i s/IPADDR.*/IPADDR='+ip+'/g /etc/sysconfig/network-scripts/ifcfg-'+eth
		 def res= com.execute()	
 		 res.consumeProcessOutput(out, err)
		 res.waitForOrKill(1000)
		 def co='sed -i s/NETMASK.*/NETMASK='+netmast+'/g /etc/sysconfig/network-scripts/ifcfg-'+eth
		 def re= co.execute()	
 		 re.consumeProcessOutput(out, err)
		 re.waitForOrKill(1000)
		 def c='sed -i s/GATEWAY.*/GATEWAY='+gateway+'/g /etc/sysconfig/network-scripts/ifcfg-'+eth
		 def r= c.execute()	
 		 r.consumeProcessOutput(out, err)
		 r.waitForOrKill(1000)
		 return err.toString()		 
}

def updateHostGateWay(def gateway) {
		 def out = new StringBuffer(), err = new StringBuffer()
		 def command='ip route add default via '+gateway+' ; ip route change default via '+gateway
		 def result =["bash", "-c", command].execute()
 		 result.consumeProcessOutput(out, err)
		 result.waitForOrKill(1000)
		 return err.toString()			 	
}

def updateHostDns(def eth,def dns) {
		 def out = new StringBuffer(), err = new StringBuffer()
		 def dnss=dns.split(',')
		 def command='echo \'nameserver '+dnss[0]+'\'> /etc/resolv.conf'
		 def result =["bash", "-c", command].execute()
		 result.consumeProcessOutput(out, err)
		 result.waitForOrKill(1000)	
		 if(dnss.length>1){
			for(int i=1;i<dnss.length;i++)  
			{  
				def _dns=dnss[i];
				if(!_dns.equals("")){
			     	def _command='echo \'nameserver '+_dns+'\'>> /etc/resolv.conf'
				 	def _result =["bash", "-c", _command].execute()
				 	_result.consumeProcessOutput(out, err)
		 			_result.waitForOrKill(1000)	
		 		 }
			} 
		 }
		 
		 if(dnss.length>0){
			for(int i=0;i<dnss.length;i++)  
			{  
				def _dns=dnss[i];
				if(!_dns.equals("")){
					def index = i + 1
			     	def _command='cat /etc/sysconfig/network-scripts/ifcfg-'+eth+' | grep DNS'+index
				 	def restest = ["bash", "-c", _command].execute().text.trim()	
				 	if(restest.equals("")) {
				 		def comm = 'echo -e \'DNS'+index+'='+_dns.trim()+'\' >> /etc/sysconfig/network-scripts/ifcfg-'+eth
				 		def resu= ["bash", "-c", comm].execute()
						resu.consumeProcessOutput(out, err)
						resu.waitForOrKill(1000)
				 	}else{
				 		def com='sed -i s/DNS'+index+'.*/DNS'+index+'='+_dns.trim()+'/g /etc/sysconfig/network-scripts/ifcfg-'+eth
						def res= com.execute()	
						res.consumeProcessOutput(out, err)
						res.waitForOrKill(1000)
				 	}
		 		 }
			} 
		 }
		 
		 return err.toString()
		 
}	

def updateSyncServerDate(def status,def server) {
		StringBuffer stdoutO = new StringBuffer(); 
		StringBuffer stderrO = new StringBuffer(); 
		 def crons=[]	
		'crontab -l'.execute().text.eachLine {
		  if(!it.contains('ntpdate')){
			 crons<<it
		  }
		}
		if(status=='1'){
		  def command= 'ntpdate '+server
		  def result= command.execute().text
		  if(result.equals("")) {
		  	return -1;
		  }
		  crons << '* */1 * * *  /usr/sbin/ntpdate '+server
		}
		def proc='crontab'.execute()
		def writer = new PrintWriter(new BufferedOutputStream(proc.out)); 
		crons.each{
			writer.println(it)
		}
        writer.close(); 
	    proc.consumeProcessOutput(stdoutO, stderrO); 
	    proc.waitForOrKill(1000)
		return proc.exitValue(); 
}	

def ret = 
[
    'hostname':hostname,
    'processormhz':processormhz,
    'processorsize':processorsize,
    'disks': disks,
    'mem': mem,
    'sys': sys,
    'dns': dns,
    'ips': ips,
    'netflow': netflow
]

return ret
